package com.youlu.campus.web.config.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求计时 过滤器
 *
 * @Description: RequestTimeFilter
 * @Date 2025/8/11
 * @module RequestTimeFilter
 * @author: su
 */
@Slf4j
public class RequestTimeFilter extends OncePerRequestFilter {

    private static final int MAX_TIME = 1000;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 记录请求开始时间
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            // 继续处理请求
            filterChain.doFilter(request, response);
        } finally {
            stopWatch.stop();
            long totalTimeMillis = stopWatch.getTotalTimeMillis();
            // 超过1秒输出日志
            if (totalTimeMillis > MAX_TIME) {
                log.error("request time url:{},method:{},time:{} ms", request.getRequestURI(), request.getMethod(), totalTimeMillis);
            }
        }
    }
}
